package com.briup.jd2407cms.utils;

import com.briup.jd2407cms.config.UploadConfig;
import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @BelongsProject: cms2
 * @BelongsPackage: com.briup.jd2407cms.utils
 * @Author: wangjie
 * @CreateTime: 2024-11-20  15:01
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Component
public class UploadUtils {
    @Autowired
    private UploadConfig uploadConfig;
    @Autowired
    private Gson gson;

    public String fileToOSS(MultipartFile file) throws Exception{
        log.info("文件上传");
        Configuration configuration = new Configuration(Region.autoRegion());
        UploadManager uploadManager = new UploadManager(configuration);
        Auth auth = Auth.create(uploadConfig.getAccessKey(), uploadConfig.getSecretKey());
        String s = auth.uploadToken(uploadConfig.getBucket());
        String fileName = generateFilePath(file);
        Response put = uploadManager.put(file.getInputStream(), fileName, s, null, null);
        DefaultPutRet defaultPutRet = gson.fromJson(put.bodyString(), DefaultPutRet.class);
        log.info("文件上传成功,文件地址:{}", uploadConfig.getBaseUrl() + fileName);
        return uploadConfig.getBaseUrl() + fileName;
    }
    private String generateFilePath(MultipartFile file) {
        //通过上传日期,对文件进行分类
        SimpleDateFormat format = new
                SimpleDateFormat("yyyy/MM/dd/");
        String datePate = format.format(new Date());
        //获取文件名称
        String filename = file.getOriginalFilename();
        //给文件做唯一标识
        assert filename != null;
        return datePate + UUID.randomUUID() +
                filename.substring(filename.lastIndexOf("."));
    }
}
